<?php
class PhotosController extends AppController {
	
	var $name = 'Photos';
	var $layout = 'admin';
	var $components = array('Image');
	
	/**
	 *  The AuthComponent provides the needed functionality
	 *  for login, so you can leave this function blank.
	 */
	function beforeFilter() {
		$username = $this->Auth->user ();
		$this->set ( 'username', $username ['User'] ['name'] );
		$this->Auth->allow ( 'login', 'logout' );
	}
	
	public function index() {
		$params ['order'] = 'id';
		if (isset ( $this->params ['named'] ['orderBy'] )) {
			$params ['order'] = $this->params ['named'] ['orderBy'];
			$this->set ( 'orderBy', $this->params ['named'] ['orderBy'] );
			if (isset ( $this->params ['named'] ['DESC'] )) {
				$params ['order'] .= ' DESC';
				$this->set ( 'DESC', $this->params ['named'] ['DESC'] );
			}
		}
		$photos = $this->Photo->find ( 'all', $params );
		$this->set ( 'photos', $photos );
		
		
		
		$groups = $this->Photo->find ( 'all', array ('fields' => 'DISTINCT group') );
		$array ['-1'] = '--select--';
		$array ['-2'] = '--other--';
		
		foreach ( $groups as $group ) {
			$array [$group ['Photo'] ['group']] = $group ['Photo'] ['group'];
		}
		$this->set ( 'groups', $array );
		
		
		
		$this->set('pageTitle', $this->pageTitle = 'Photos');
		
	}
	
	public function delete($id = NULL) {
		if ($id) {
			if ($this->Photo->delete ( $id )) {
				$this->Session->setFlash ( 'File deleted successfuly!' );
				$this->redirect ( array ('action' => 'index' ) );
			} else {
				$this->Session->setFlash ( 'Failed! Please try again or contact to administrator.' );
				$this->redirect ( array ('action' => 'index' ) );
			}
		
		} else {
			$this->Session->setFlash ( 'Failed! No such file.' );
			$this->redirect ( array ('action' => 'index' ) );
		
		}
	}
	
	public function add() {
		if (! empty ( $this->data )) {
			
			$i=1;
			while(!empty($this->data['Photo']['file'.$i]['name'])){
				$this->Photo->create();
				$saveable = array(
					//"name" => $this->data['Photo']['name'],
				    //"group" => ($this->data ['Photo']['group'] == -2) ? $this->data['Photo']['group_other'] : $this->data ['Photo']['group'],
				);
				if( $saveable['filename'] = $this->Image->upload_image_and_thumbnail($this->data['Photo'],'file'.$i,640,80,"Photos",true) ){
					//$this->Watermark->watermark('img/Photos/big/'.$this->data['Photo']['filename']);
					$this->Photo->save($saveable);
					$i++;
				}else{
					$this->Session->setFlash ( 'Failed to add file!' );
					$this->redirect ( array ('action' => 'index' ) );
					return;
				}
			}	
			
			$this->Session->setFlash ( 'File(s) added successfuly!' );
			$this->redirect ( array ('action' => 'index' ) );
			
		}
		$this->set('pageTitle', $this->pageTitle = 'Add a Photo');
	}
	
}

?>